<!DOCTYPE html>
<html lang="en" data-layout="vertical" data-sidebar-visibility="show" data-topbar="light" data-sidebar="dark"
      data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable" data-bs-theme="dark">
<head>
    <meta charset="utf-8"/>
    <title>{% block title %}{% endblock title %} OmniStore | OMS System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta content="OmniStore warehouse and order system" name="description"/>
    <meta content="shvedvi" name="author"/>
    <!-- App favicon -->
    <link rel="shortcut icon" href="{{ url_for('static' ,path='images/favicon.ico') }}"/>

    {% block css %}
        <!-- Layout config Js -->
        <!-- Bootstrap Css -->
        <link href="{{ url_for('static' ,path='css/bootstrap.min.css') }}" id="bootstrap-style" rel="stylesheet"
              type="text/css"/>
        <!-- Icons Css -->
        <link href="{{ url_for('static' ,path='css/icons.min.css') }}" rel="stylesheet" type="text/css"/>
        <!-- App Css-->
        <link href="{{ url_for('static' ,path='css/app.min.css') }}" id="app-style" rel="stylesheet" type="text/css"/>
        <!-- custom Css-->
        <link href="{{ url_for('static' ,path='css/custom.min.css') }}" id="app-style" rel="stylesheet"
              type="text/css"/>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap-table@1.22.4/dist/bootstrap-table.min.css" rel="stylesheet">
        <style>
            .footer {
                border-top-left-radius: 15px;
                border-top-right-radius: 15px;
            }

            .card-header {
                border-bottom: hidden;
            }

            .modal-content {
                border-radius: 15px;
            }

            .dropdown-menu {
                border-radius: 15px;
            }


            .card {
                margin-bottom: 1rem;
            }

            .choices__list--dropdown {
                border-radius: 15px !important;
                width: max-content;
            }

            .is-disabled .choices__inner {
                border: 0;
            }


            .choices__inner .choices__list {
                background: transparent;
                background: transparent;
                background-color: transparent;
                border-radius: 15px !important;
            }

            .choices[data-type*=select-multiple] .choices__list--dropdown, .choices[data-type*=text] .choices__list--dropdown {
                padding-bottom: 10px;
                border-radius: 15px !important;
            }

            .choices[data-type*=select-multiple] .choices__inner, .choices[data-type*=text] .choices__inner {
                cursor: text;
                padding-right: .9rem;
                border-radius: 10px !important;
            }


            input[type="date"] {
                position: relative;
            }

            ::-webkit-datetime-edit-year-field:not([aria-valuenow]),
            ::-webkit-datetime-edit-month-field:not([aria-valuenow]),
            ::-webkit-datetime-edit-day-field:not([aria-valuenow]) {
                color: transparent;
            }


            .choices {
                position: relative;
                margin-bottom: 0px;
                font-size: 16px;
                border-radius: 15px;
            }

            .is-invalid {
                border: 1px solid var(--vz-form-invalid-border-color) !important;
                border-radius: 15px !important;
            }

            .is-invalid::after {
                position: absolute;
                font-weight: 900;
                content: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23f7666e'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23f7666e' stroke='none'/%3e%3c/svg%3e");
                color: var(--vz-form-invalid-border-color);
                font-size: 20px;
                right: 40px;
                border-radius: 15px !important;
            }

            .is-valid {
                border: 1px solid var(--vz-form-valid-border-color) !important;
                border-radius: 10px !important;
            }

            .is-valid::after {
                position: absolute;
                font-weight: 900;
                background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%233cd188' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
                background-position: right calc(1.375em + 1.5rem) center !important;
                color: var(--vz-form-valid-border-color);
                font-size: 20px;
                right: 40px;
            }

            .choices[data-type*=select-one] .choices__inner {
                border-radius: 10px !important;
            }

            .choices[data-type*=select-one] .choices__input {
                border-radius: 10px !important;
            }

            .card {
                border-radius: 20px;
            }

            .card-header {
                border-radius: 20px;
            }

            .btn {
                border-radius: 10px;
            }

            .card-header:first-child {
                border-radius: 10px;
            }

            .table {
                border-radius: 20px;
            }

            .table-responsive {
                border-radius: 20px;
            }

            .form-control {
                border-radius: 10px;
            }

            .form-control.is-valid {
                border-radius: 10px;
                background-position: right calc(1.375em + 1.5rem) center !important;
            }

            .app-menu {
                border-bottom-left-radius: 20px;
                border-bottom-right-radius: 20px;
            }

            .page-title-box {
                border-bottom-left-radius: 20px;
                border-bottom-right-radius: 20px;
            }


            select option[selected] {
                background-color: var(--vz-form-valid-border-color)
            }

            .modal-xl {
                min-width: 80%;
            }
        </style>
    {% endblock css %}
</head>

<body>
<div id="websocket_bus" hx-ext="ws" ws-connect="{{ ws }}"></div>
<div class="position-fixed top-0 end-0 p-3">
    <div id="toast" class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive"
         aria-atomic="true">
        <div class="d-flex">
            <div id="toast-body" class="toast-body"></div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"
                    aria-label="Close"></button>
        </div>
    </div>
</div>
<!-- Begin page -->

<div id="layout-wrapper">
    <div hx-get="/bff/topbar" hx-trigger="load"></div>
    <div id="errors"></div>
    {% block sidebar %}
        {% include "partials/sidebar.html" %}
    {% endblock sidebar %}
    <div id="htmx_content">
        {% block content %}
            <!--<div hx-get="/" hx-trigger="load"></div>-->
        {% endblock %}
    </div>

    <div hx-get="/bff/footer" hx-trigger="load">
        {% block footer %}

        {% endblock footer %}
    </div>

    <div id="trash"></div>
</div>

{% block extra_content %}
{% endblock extra_content %}

<!-- END layout-wrapper -->
{% block right_sidebar %}
    {% include "partials/customizer.html" %}
{% endblock right_sidebar %}

{% block javascript %}
    <!-- JAVASCRIPT -->

    <script src="{{ url_for('static' ,path='libs/bootstrap/dist/js/bootstrap.bundle.min.js') }}"></script>
    <script src="{{ url_for('static' ,path='libs/simplebar/dist/simplebar.min.js') }}"></script>
    <script src="{{ url_for('static' ,path='libs/node-waves/dist/waves.min.js') }}"></script>
    <script src="{{ url_for('static' ,path='libs/feather-icons/dist/feather.min.js') }}"></script>
    <script src="{{ url_for('static' ,path='js/pages/plugins/lord-icon-2.1.0.js') }}"></script>
    <script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js" type="text/javascript"></script>
        <script src="https://cdn.jsdelivr.net/gh/alumuko/vanilla-datetimerange-picker@latest/dist/vanilla-datetimerange-picker.js"></script>
    <script src="{{ url_for('static' ,path='js/plugins.js') }}"></script>
    <script src="https://cdn.lordicon.com/lordicon.js"></script>
    <script src="{{ url_for('static' ,path='js/app.js') }}"></script>

    <script src="{{ url_for('static' ,path='js/htmx.min.js') }}"></script>
    <script src="{{ url_for('static' ,path='js/ws.js') }}"></script>
    <script src="{{ url_for('static' ,path='js/json-enc.js') }}"></script>
    <script>
        function getCookieValue(name) {
            const nameString = name + "="

            const values = document.cookie.split(";").filter(item => {
                return item.includes(nameString)
            })
            if (values.length) {
                let value = []
                for (let val in values) {
                    let is_value = values[val].split('=').filter(item => {
                        return item.replace(' ', '') === name
                    })
                    if (is_value.length) {
                        value = values[val]
                        break
                    }
                }
                if (value.length) {
                    return value.substring(nameString.length, value.length).replace('=', '')
                }
            } else {
                return null
            }
        }

        function removeCookie(sKey, sPath, sDomain) {
            document.cookie = encodeURIComponent(sKey) +
                "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" +
                (sDomain ? "; domain=" + sDomain : "") +
                (sPath ? "; path=" + sPath : "");
        }

        function parseJwt(token) {
            var base64Url = token.split('.')[1];
            var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
            var jsonPayload = decodeURIComponent(window.atob(base64).split('').map(function (c) {
                return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
            }).join(''));

            return JSON.parse(jsonPayload);
        }

        // auth is a promise returned by our authentication system

        // await the auth token and store it somewhere

        var authToken = null
        // gate htmx requests on the auth token
        htmx.on("htmx:confirm", (e) => {
            let authToken = getCookieValue('token');
            // if there is no auth token
            if (authToken == null && !window.location.pathname.includes('login')) {
                e.preventDefault()
                window.history.pushState('Login', 'Login', '/basic/login');
                console.log('redirect login')
                htmx.ajax('GET', '/basic/login', {
                    target: '#htmx_content', headers: {
                        'HX-Replace-Url': 'true'
                    }
                })
                //console.log(authToken)
            }
        });

        async function refreshToken() {
            let user = {
                token: getCookieValue('token').replace('=', ''),
                refresh_token: getCookieValue('refresh_token').replace('=', '')
            };
            console.log('refreshing token')
            let response = await fetch('/basic/user/refresh', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(user)
            });
            let result = await response.json();
            const parsed = parseJwt(result.token)
            const expires = await new Date(parsed.exp * 1000)
            document.cookie = "token=" + result.token + "; expires=" + expires + ";path=/;"
            document.cookie = "refresh_token=" + result.token + "; expires=" + expires + ";path=/;"
            return true

        }

        async function checkAuth() {
            var authToken = getCookieValue('token')
            if (!authToken) {
                authToken = getCookieValue('refresh_token')
                if (authToken) {
                    authToken = refreshToken()
                    authToken = getCookieValue('token')
                }
            }
            if (!authToken) {
                return false
            }
            var tokenData = parseJwt(authToken)
            var now = Date.now() / 1000
            if (tokenData.exp <= now) {
                await refreshToken()
            }
            return true
        }

        // add the auth token to the request as a header
        htmx.on("htmx:configRequest", (e) => {
            //e.detail.headers["AUTH"] = authToken
            console.log('check cookie')
            const res = checkAuth()
            e.detail.headers["Authorization"] = getCookieValue('token')
        })
        htmx.on("htmx:afterRequest", (e) => {
            //e.detail.headers["AUTH"] = authToken
            if (authToken == null) {
                //console.log('afterRequest')
                if (e.detail.xhr.status || 200) {
                    e.detail.shouldSwap = true;
                    e.detail.isError = false;
                }
            }
        })
        htmx.on('htmx:beforeSwap', function (evt) {
            if (evt.detail.xhr.status === 200) {
                // do nothing
            } else if (evt.detail.xhr.status === 404) {
                // alert the user when a 404 occurs (maybe use a nicer mechanism than alert())
                var myToast = Toastify({
                    text: evt.detail.pathInfo.requestPath + ' + ' + evt.detail.xhr.responseText,
                    duration: 3000,
                    close: true,
                    style: {
                        background: "#e94e1d",
                    },

                })
                myToast.showToast();
            } else if (evt.detail.xhr.status === 403) {
                // Запрещено
                var errors = htmx.find("#errors");
                evt.detail.target = errors
                evt.detail.shouldSwap = true;
                evt.detail.isError = false;
            } else if (evt.detail.xhr.status === 401 && !window.location.pathname.includes('login')) {
                // Запрещено
                debugger
                window.history.pushState('Login', 'Login', '/basic/login');
                htmx.ajax('GET', '/basic/login', {
                    target: '#htmx_content', headers: {
                        'HX-Replace-Url': 'true'
                    }
                })
            } else if (evt.detail.xhr.status === 418) {
                // if the response code 418 (I'm a teapot) is returned, retarget the
                // content of the response to the element with the id `teapot`
                evt.detail.shouldSwap = true;
                evt.detail.target = htmx.find("#teapot");

            } else {
                var myToast = Toastify({
                    text: evt.detail.xhr.responseText,
                    duration: 3000,
                    close: true,
                    style: {
                        background: "#e94e1d",
                    },

                })
                myToast.showToast();
            }
        });
        //htmx.logger = function (elt, event, data) {
        //    if (console) {
        //        console.log(event, elt, data);
        //    }
        //};
        htmx.on('htmx:wsConfigSend', (e) => {
            console.log('wsConfigSend')
            console.log(e);
            e.detail.headers["Authorization"] = getCookieValue('token')
        })
        htmx.on('htmx:wsBeforeMessage', (e) => {
            console.log('wsBeforeMessage')
            const message = JSON.parse(e.detail.message)
            console.log(message)
            if (message.message_type === 'COMPANY_CHANGED') {
                refreshToken()
                var table = htmx.find("table")
                if (table) {
                    htmx.trigger(table, 'update')
                }
                var form = htmx.find("form")
                if (form) {
                    htmx.trigger(form, 'update')
                }
                var modal = htmx.find("modal")
                if (modal) {
                    htmx.trigger(modal, 'update')
                }
            } else if (message.tag === 'MODEL') {}
            console.log(message)
                var element = htmx.find(message.message)
                htmx.trigger(element, 'update')
        })

        function hideModals(modal) {
            //debugger
            if (modal){
                modal = document.getElementById(modal)
                let currentModal = bootstrap.Modal.getInstance(modal)
                if (currentModal) {
                    currentModal.hide()
                }
            } else {
            var $modals = document.querySelectorAll('.modal')
            $modals.forEach(modal => {
                let currentModal = bootstrap.Modal.getInstance(modal)
                if (currentModal) {
                    currentModal.hide()
                }
            })
            var $modals = document.querySelectorAll('.modal-backdrop')
            $modals.forEach(back => {
                if (back) {
                    back.remove()
                }
                var body = document.body
                body.style.removeProperty('overflow');
            })
        }}

        htmx.on('htmx:afterSwap', (e) => {
            //trans()
        })
        var body_init = null
        htmx.on('htmx:xhr:loadstart', (e) => {
            if (!body_init) {

                body_init = 1
            }
        })
    </script>
    <script>
        window.doN = true;
    </script>
    <!-- App js -->
{% endblock javascript %}

</body>
<script>
    //Не разобрался почему так, но без этого не работает
    const timerId = setTimeout(() => {
        main()
    }, 1000)
</script>


</html>